package cn.lysj.framework.customer.util;

import cn.lysj.framework.common.utils.http.HttpUtil;
import cn.lysj.framework.common.utils.web.ParamUtil;

import cn.lysj.framework.customer.domain.Customer;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.log4j.Log4j;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.Map;

/**
 * 微信公众号操作相关工具类
 */
@Log4j
public class WxAuzLoginUtil {
    public static final String GET_WEB_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token"; //获取网页授权
    public static final String GET_WX_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token"; // get请求,获取公众号token,grant_type=client_credential
    public static final String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo";
    public static final String LOGIN_PAGE_URL = "http://www.ljajjc.com/" + "wxstore/login.html";
    public static String WX_ACCESS_TOKEN = "";// access_token
    public static Long WX_ACCESS_TOKEN_EXPIRES_IN = 0L;// access_token的有效期

    public static final String wx_app_id = "wx81fc3b3d2eb1ea39"; //微信公众号APPID
    public static final String wx_app_secret = "4783f968aafa08c6e8c0c08793382ab0";// 微信公众号秘钥


    ////////////////////////////////////////////////////////////
    public static final Type type = new TypeToken<Map<String, String>>() {
    }.getType();

    /**
     * 获取OpenId
     *
     * @param request
     * @return opid
     */
    public static String getOpenId(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        String code = request.getParameter("code");
        if (ParamUtil.isBlank(code)) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("appid=").append(wx_app_id).append("&secret=").append(wx_app_secret).append("&code=").append(code).append("&grant_type=authorization_code");
        String tokenJson = HttpUtil.sendGet(GET_WEB_ACCESS_TOKEN_URL, sb.toString());
        Gson gson = new Gson();
        Map<String, String> map = gson.fromJson(tokenJson, type);
        String openId = map.get("openid");
        return openId;
    }

    ////////////////////////////////////////////////////////////

    /**
     * 获取access_token
     */
    public static String getAccessToken() {
        if (WX_ACCESS_TOKEN_EXPIRES_IN > System.currentTimeMillis()) { // 还在有效期内
            return WX_ACCESS_TOKEN;
        } else { // 超过有效期限,重新获取
            StringBuilder sb = new StringBuilder("grant_type=client_credential");
            sb.append("&appid=").append(wx_app_id);
            sb.append("&secret=").append(wx_app_secret);
            String tokenJson = HttpUtil.sendGet(GET_WX_ACCESS_TOKEN_URL, sb.toString());
            // System.out.println(tokenJson);
            Gson gson = new Gson();
            Map<String, String> map = gson.fromJson(tokenJson, type);
            String accessToken = map.get("access_token");
            if (ParamUtil.isBlank(accessToken)) {
                log.error("获取Access_Token错误:" + tokenJson);
                return null;
            }
            WX_ACCESS_TOKEN = accessToken;
            WX_ACCESS_TOKEN_EXPIRES_IN = System.currentTimeMillis() + 7000 * 1000; // 官方时间7200秒,这里设置成7000秒
            return WX_ACCESS_TOKEN;
        }
    }

    ////////////////////////////////////////////////////////////


    public static Customer getUserInfo(HttpServletRequest request) {
        Customer wxCustomer = new Customer();
        if (request == null) {
            return wxCustomer;
        }
        // 第二步：通过code换取网页授权access_token
        String code = request.getParameter("code");
        if (ParamUtil.isBlank(code)) {
            return wxCustomer;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("appid=").append(wx_app_id).append("&secret=").append(wx_app_secret).append("&code=").append(code).append("&grant_type=authorization_code");
        String tokenJson = HttpUtil.sendGet(GET_WEB_ACCESS_TOKEN_URL, sb.toString());
        //		System.out.println("// 第二步:" + tokenJson);
        Gson gson = new Gson();
        Map<String, String> map = gson.fromJson(tokenJson, type);
        String openId = map.get("openid");
        String access_token = map.get("access_token");
        if (ParamUtil.isBlank(openId) || ParamUtil.isBlank(access_token)) {
            return wxCustomer;
        }


        // 第四步：拉取用户信息(需scope为 snsapi_userinfo)
        StringBuilder sb2 = new StringBuilder();
        sb2.append("access_token=").append(access_token).append("&openid=").append(openId).append("&lang=zh_CN ");
        String userinfoJson = HttpUtil.sendGet(getUserInfoUrl, sb2.toString());
        //		System.out.println("// 第四步:" + userinfoJson);
        userinfoJson = userinfoJson.replace("[]", "\"\"");
        Map<String, String> userinfoMap = gson.fromJson(userinfoJson, type);
        if (ParamUtil.isBlank(userinfoMap.get("openid"))) {
            return wxCustomer;
        }

        // 将获取到的用户信息返回出去
        wxCustomer.setFlagId(userinfoMap.get("openid"));
        wxCustomer.setNickName(ExpressFiler.emojiFilter(userinfoMap.get("nickname")));
        wxCustomer.setHeadPhoto(userinfoMap.get("headimgurl"));
        wxCustomer.setCity(userinfoMap.get("city"));
        wxCustomer.setCreateTime(new Date());
        wxCustomer.setCustomerType(2); //设置用户类型为微信用户
        return wxCustomer;
    }


}
